package com.face.zf.service.impl;

import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.face.model.facerec.FaceRecModel;
import com.face.zf.domain.pojo.FacePackage;
import com.face.zf.service.FaceCompareService;
import com.face.zf.util.Base64Utils;
import com.face.zf.model.FaceModel;
import com.face.zf.util.PropertiesPool;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @Author: (ﾉ ◠ ‿ ◠)ﾉ wangYu
 * @CreateTime: 2025-06-26
 * @ContactMe WECHAT-> wy10012311   QQ-> 1569350611
 * @Description:
 */
@Service
public class FaceCompareServiceImpl implements FaceCompareService {

    private static final Logger log = LoggerFactory.getLogger(FaceCompareServiceImpl.class);

    protected static Properties application = PropertiesPool.obtainProperties();

    @Override
    public FacePackage compare(String imageOneBase64, String imageTwoBase64) {
        try {
            byte[] imageData1 = Base64Utils.decodeBase64(imageOneBase64);
            byte[] imageData2 = Base64Utils.decodeBase64(imageTwoBase64);
            FaceRecModel faceRecModel = FaceModel.getFaceRecModel();
            long startTime = System.currentTimeMillis();
            R<Float> similarResult = faceRecModel.featureComparison(imageData1, imageData2);
            long endTime = System.currentTimeMillis();
            log.info("本次比对耗时:{}", (endTime - startTime) / 1000.0 + "s");
            if (similarResult.isSuccess()) {
                double similarity = similarResult.getData();
                //特定模型补偿
                similarity = modelCompaensation(similarity);
                double scaledSimilarity  = similarity * 100;
                String scaledResult = String.format("%.2f", scaledSimilarity);
                log.info("本次识别相似度为:{}", scaledResult);
                return new FacePackage(200, scaledResult, "success");
            } else {
                String message = similarResult.getMessage();
                FacePackage facePackage = new FacePackage();
                facePackage.setCode(401);
                facePackage.setSimilarity("0");
                facePackage.setMessage(message);
                log.warn("人脸比对失败：{}", message);
                return facePackage;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //模型补偿添加0.1
    private static double modelCompaensation(double similarity) {
        if(application.getProperty("face.detection.model.name").equals("YOLOV5_FACE_320") &&
                application.getProperty("face.recognition.model.name").equals("SeetaFace6Model")){
            if (similarity < 0.8 & similarity > 0.4) {
                similarity += 0.15;
            }
        }
        return similarity;
    }

    //    private final OkHttpClient client = createUnsafeOkHttpClient();


//    private OkHttpClient createUnsafeOkHttpClient() {
//        try {
//            final TrustManager[] trustAllCerts = new TrustManager[]{
//                    new X509TrustManager() {
//                        @Override
//                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
//                        }
//
//                        @Override
//                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
//                        }
//
//                        @Override
//                        public X509Certificate[] getAcceptedIssuers() {
//                            return new X509Certificate[]{};
//                        }
//                    }
//            };
//            final SSLContext sslContext = SSLContext.getInstance("SSL");
//            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
//            final HostnameVerifier hostnameVerifier = (hostname, session) -> true;
//            return new OkHttpClient.Builder()
//                    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
//                    .hostnameVerifier(hostnameVerifier)
//                    .connectTimeout(30, TimeUnit.SECONDS)
//                    .readTimeout(30, TimeUnit.SECONDS)
//                    .build();
//        } catch (Exception e) {
//            throw new RuntimeException("无法创建不安全的 HttpClient", e);
//        }
//    }



//    @Value("${pirs.url}")
//    String pirsUrl;
//
//    public String pirsCompare(HttpServletRequest request) throws IOException {
//        // 1. 获取请求头
//        String appCode = request.getHeader("app_code");
//        String resourceId = request.getHeader("resource_id");
//        String taskId = request.getHeader("taskId");
//
//        // 2. 读取JSON请求体
//        StringBuilder jsonBody = new StringBuilder();
//        try (BufferedReader reader = request.getReader()) {
//            String line;
//            while ((line = reader.readLine()) != null) {
//                jsonBody.append(line);
//            }
//        }
//
//        RequestBody body = RequestBody.create(
//                MediaType.parse("application/json; charset=utf-8"), jsonBody.toString());
//        System.out.println(jsonBody);
//
//        System.out.println("app_code: " + appCode);
//        System.out.println("resource_id: " + resourceId);
//        System.out.println("taskId: " + taskId);
//
//        Request build = new Request.Builder()
//                .url(pirsUrl)
//                .addHeader("app_code", appCode)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("resource_id", resourceId)
//                .addHeader("taskid", taskId)
//                .post(body).build();
//        Call call = client.newCall(build);
//        try {
//            System.out.println("===============请求成功=============");
//            Response response = call.execute();
//            if (StringUtils.isEmpty(response.body())) {
//                return "数据为空";
//            }
//            return response.body().string();
//        } catch (IOException e) {
//            System.out.println("===============请求失败===============");
//            e.printStackTrace();
//            return "{\"status\":\"error\", \"message\":\"" + e.getMessage() + "\"}";
//        }
//    }
}
